<template>
  <div class="redeemCode hideScrollBar" ref="scrollEl">
    <!-- 内容部分 -->
    <div class="content">
      <!-- 导航 -->
      <NavBar
        isFixed
        :title="$t('activity.fldu')"
        :isTransparent="pageData.whiteTheme"
        :whiteTheme="pageData.whiteTheme"
        :navScorllOffset="60"
        navScorllColor="#fff"
        gradientTitleColor="#141924"
        :scrollEl="scrollEl"
        @thresholdChange="(val) => (pageData.whiteTheme = !val)"
      />
      <!-- 背景 -->
      <div style="position: relative">
        <div class="content-bg">
          <img class="content-bg-img" src="/image/activity/redeemCode-bg.png" />
          <img
            v-if="!exchangeLoading"
            class="content-bg-box"
            :src="imgUrl.redeemCodebox"
          />
          <Vue3Lottie
            v-show="exchangeLoading && AstronautJSON"
            class="content-bg-box"
            :width="lottieWidth"
            :animationData="AstronautJSON"
            :autoPlay="pauseAnimation"
            :pauseAnimation="pauseAnimation"
            :loop="false"
          />
        </div>
      </div>

      <!-- 开箱动画 -->
      <div class="box" style="padding-top: 20px"></div>
      <!-- 兑换码 -->
      <div class="codeDh">
        <!-- 输入兑换码 -->
        <div class="codeDh-top">
          <div class="codeDh-top-title">
            {{ $t("activity.dhdesc") }}
          </div>
          <div style="position: relative">
            <van-field
              class="codeDh-top-input"
              label=""
              v-model="pageData.input"
              :placeholder="$t('airdrop.qsr')"
              :formatter="inputFormatter"
            />
            <img
              class="codeDh-top-input-copy"
              src="/image/activity/input-copy.svg"
              @click.stop="getCopy"
            />
          </div>

          <!-- 提示语 -->
          <div
            class="codeDh-top-alert items-center"
            v-if="
              pageData.leftExchangeCount != null &&
              Number(pageData.leftExchangeCount) <= 0
            "
          >
            <img
              class="codeDh-top-alert-icon"
              src="/image/activity/input-alert-icon.svg"
            />
            {{ $t("activity.dhmLint") }}
          </div>
          <!-- 兑换按钮 -->
          <div
            class="codeDh-top-btn"
            :class="{ 'codeDh-top-btn-disabled': isDisabled }"
            @click.stop="exchangeRequest"
          >
            {{ $t("activity.exchange") }}
          </div>
        </div>
        <!-- 兑换规则 -->
        <div class="codeDh-bottom">
          <div class="codeDh-bottom-item">
            <img
              class="codeDh-bottom-item-icon"
              src="/image/assetDetails/desc-logo.svg"
            />
            {{ $t("activity.dhText0") }}
          </div>
          <div class="codeDh-bottom-item">
            <img
              class="codeDh-bottom-item-icon"
              src="/image/assetDetails/desc-logo.svg"
            />
            {{ $t("activity.dhText1") }}
          </div>
          <div class="codeDh-bottom-item">
            <img
              class="codeDh-bottom-item-icon"
              src="/image/assetDetails/desc-logo.svg"
            />
            {{ $t("activity.dhText2") }}
          </div>
        </div>
      </div>
    </div>
    <!-- 弹窗 -->
    <InfoPopup
      v-model:show="pageData.isShow"
      :detail="detailPopup"
      @refresh="resetBox"
    ></InfoPopup>
  </div>
</template>
<script setup name="redeemCode">
import { getExchangeCodeCountInfo, exchange } from "@/api/reward";
import { getOssFileUrl, debounce, isAndroid } from "@/utils";
import InfoPopup from "~~/components/airdrop/popupInfo.vue";
import { Vue3Lottie } from "vue3-lottie";
import { useFetch as http } from "@vueuse/core";
import { useGlobalStore } from "~~/store/global";
import * as MITO from "@zhj1214/qdjk-web";
import { JUMPAPPS } from "~/config";

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

const { t } = useI18n();
const scrollEl = ref();

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase

const imgUrl = getOssFileUrl({
  redeemCodebox: "/image/activity/redeemCode-box.png",
});
// 页面属性
const pageData = reactive({
  isShow: false,
  loading: false,
  whiteTheme: true,
  input: "",
  leftExchangeCount: null, // 剩余兑换次数
});

// 是否禁用输入框
const isDisabled = computed(() => {
  return (
    !pageData.input ||
    pageData.input.length <= 0 ||
    pageData.leftExchangeCount <= 0
  );
});

/**
 * @description: 查询兑换次数
 */
const getExchangeCodeNumRequest = () => {
  getExchangeCodeCountInfo().then((res) => {
    console.log("兑换次数", res);
    if (res) {
      pageData.leftExchangeCount = res.leftExchangeCount;
    }
  });
};

// 展示弹窗
const detailPopup = ref();
const showPopup = (val) => {
  detailPopup.value = {
    boxType: 1,
    bonusAmount: 0,
    sendAmount: val,
    isRedeemCOde: true,
  };
  pageData.isShow = true;
};

/**
 * @description: 兑换请求
 */
const exchangeLoading = ref(false);
const lottieWidth = ref(120);
const AstronautJSON = ref(null);
const pauseAnimation = ref(false);
const exchangeRequest = debounce(async () => {
  if (isDisabled.value) return;
  // 1. loading
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
  });
  try {
    const res = await exchange({
      exchangeCode: pageData.input.replace(/\s/g, ""), // 删除字符串中所有的空格
    });
    // console.log("--兑换码--", res);
    if (res && res != 1203) {
      const popupShow = () => {
        pageData.input = "";
        showPopup(res.sendAmount);
        if (pageData.leftExchangeCount >= 1) {
          pageData.leftExchangeCount = Number(pageData.leftExchangeCount) - 1;
        }
      };
      // 1. 做动画
      if (AstronautJSON.value) {
        exchangeLoading.value = true;
        setTimeout(() => {
          pauseAnimation.value = true;
        }, 1);
        // 1.2 展示弹窗
        setTimeout(() => {
          popupShow();
        }, 1100);
      } else {
        popupShow();
      }
    } else {
      resetBox();
      if (res == 1203) {
        getExchangeCodeNumRequest();
      }
    }
  } catch (error) {
    MITO.log({
      message: `兑换码-接口请求失败:${error}`,
      tag: "兑换码-接口报错",
      level: "high",
      ex: "测试",
    });
  }
}, 500);

const resetBox = () => {
  exchangeLoading.value = false;
};
onMounted(() => {
  // 1.买点
  firebase?.logEvent("BDC_H5_RedeemCode_PUV");
  // 2.兑换次数
  getExchangeCodeNumRequest();
  // showPopup(8954);
  // 3.获取动画
  http("https://bdc.btcdana.org/fx/lottie/rewards/rewards.json").then((res) => {
    if (res.data.value) AstronautJSON.value = JSON.parse(res.data.value);
  });
});

/**
 * @description: 获取剪贴板内容
 */
const getCopy = () => {
  // 1. 获取剪贴板内容
  bridge.getAppCopyValue(
    (val) => {
      console.log("获取剪贴板内容:", val);
      if (val) {
        pageData.input = val;
        showToast(t("mvp.other.ztcg"));
      } else if (val === false) {
        showToast(`${t("mvp.other.bzcjtb")},${t("mvp.other.upInstall")}`);
      } else {
        showToast(t("mvp.other.jtbwk"));
      }
    },
    isAndroid.value,
    JUMPAPPS().getAppCopy()
  );
};

// 输入框-格式校验
const inputFormatter = (value) => {
  // 删除字符串中的特殊字符
  if (value && value.length > 0) {
    value = value.replace(/[^a-zA-Z0-9]/g, "");
  }
  return value;
};
</script>
<style lang="scss" scoped>
.redeemCode {
  position: relative;
  background-color: #fff;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;

  .content {
    position: relative;
    &-bg {
      position: absolute;
      top: -95 * 2px;
      left: 0px;
      background: linear-gradient(
        180deg,
        #1586ff 0.01%,
        rgba(199, 245, 255, 0.55) 45.13%,
        rgba(199, 223, 255, 0.3) 113.92%
      );

      width: 100vw;
      height: 574 * 2px;
      &-img {
        position: absolute;
        top: 125px;
        margin-left: 5%;
        width: 90%;
      }
      &-box {
        position: absolute;
        top: 205px;
        left: calc(50% - 110px);
        height: 120 * 2px;
      }
    }
  }
}
.box {
  position: relative;
  z-index: 9;
  height: 180 * 2px;
}
.codeDh {
  border-top-left-radius: 12 * 2px;
  border-top-right-radius: 12 * 2px;
  position: relative;
  z-index: 9;
  background: linear-gradient(
    180deg,
    rgba(255, 255, 255, 0.7) 0%,
    rgba(255, 255, 255, 0.8) 100%
  );
  border: 1px solid rgba(255, 255, 255, 0.4);
  backdrop-filter: blur(30px);
  padding: 20 * 2px 15 * 2px;
  &-top {
    position: relative;
    padding: 20 * 2px 15 * 2px;
    background-color: #fff;
    border-radius: 12 * 2px;
    margin-bottom: 24 * 2px;
    &-title {
      color: #002853;
      font-size: 15 * 2px;
      font-weight: 590;
      margin-bottom: 24 * 2px;
    }
    &-input {
      margin-bottom: 10 * 2px;
      background: rgba(115, 119, 128, 0.08);
      border-radius: 6 * 2px;
      &-copy {
        position: absolute;
        top: 25px;
        right: 30px;
        z-index: 99;
        width: 20 * 2px;
        height: 20 * 2px;
      }
    }

    &-alert {
      color: #ff4040;
      font-size: 11 * 2px;
      // margin-bottom: 24 * 2px;
      &-icon {
        width: 14 * 2px;
        height: 14 * 2px;
        margin-right: 4 * 2px;
      }
    }
    &-btn {
      margin-top: 24 * 2px;
      background: #007bff;
      border-radius: 4 * 2px;
      color: #fff;
      text-align: center;
      font-size: 15 * 2px;
      font-weight: 590;
      padding: 12 * 2px 0;
      &-disabled {
        background: #a0ceff !important;
      }
    }
  }
  &-bottom {
    position: relative;
    padding: 20 * 2px 15 * 2px;
    margin-bottom: 24 * 2px;
    &-item {
      display: flex;
      align-items: flex-start;
      color: #999da7;
      font-size: 12 * 2px;
      margin-bottom: 15 * 2px;
      line-height: 16 * 2px;
      &-icon {
        width: 11 * 2px;
        height: 11 * 2px;
        margin-right: 8 * 2px;
      }
    }
  }
}
.banner {
  margin-bottom: 10 * 2px;
  width: 100vw;
  padding: 15 * 2px;
  background-color: #fff;
  border-radius: 24px;
  overflow: hidden;
  &-img {
    border-radius: 12px;
    overflow: hidden;
    background-color: #fff;
    border-radius: 24px;
    height: 80 * 2px;
    // width: 363 * 2px;
    width: 100%;
  }
}
</style>
<style lang="scss">
.codeDh-top-input {
  .van-cell__value {
    .van-field__control {
      width: calc(100% - 22 * 2px);
    }
  }
}
</style>
